package Thread_lock;

import sun.misc.Unsafe;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/29
 * Time:17:55
 * 线程安全 - Atomic*
 **/

public class Demo2 {
    //Unsafe

    private static AtomicInteger count = new AtomicInteger(0);

    //最大循环次数
    public static final int MAXSIZE = 10_0000;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < MAXSIZE; i++) {
                    count.getAndIncrement();
                    //count.incrementAndGet();
                }
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < MAXSIZE; i++) {
                    count.getAndDecrement();
                }
            }
        });
        t2.start();

        t1.join();
        t2.join();

        System.out.println(count);

        /*Atomic 举例
        AtomicInteger count = new AtomicInteger(0);
        count.getAndIncrement();//i++
        count.incrementAndGet();//++i

        System.out.println(count.getAndIncrement());
        System.out.println(count.incrementAndGet());*/
    }
}
